package main

import (
	"fmt"
	"math"
	"net/http"
	_ "net/http/pprof"
	"runtime"
	"runtime/pprof"
	"strconv"
	"sync"
	"time"
)

func write(w http.ResponseWriter, data []byte) {
	_, _ = w.Write(data)
}

func count(w http.ResponseWriter, r *http.Request) {
	write(w,[]byte(strconv.Itoa(runtime.NumGoroutine())))
}

func query(w http.ResponseWriter, r *http.Request) {
	c := make(chan byte)

	go func() {
		c <- 0x31
	}()

	go func() {
		c <- 0x32
	}()

	go func() {
		c <- 0x33
	}()

	rs := make([]byte, 0)
	for i := 0; i < 2; i++ {
		rs = append(rs, <-c)
	}

	write(w, rs)
}

func goroutineStack(w http.ResponseWriter, r *http.Request) {
	_ = pprof.Lookup("goroutine").WriteTo(w, 1)
}

func doAllocate(nKB int, wg *sync.WaitGroup) {
	var slice []byte
	for i := 0; i < nKB; i++ {
		t := make([]byte, 1024) // 1KB
		slice = append(slice, t...)
		// 大约会执行 50 秒，方便观察内存增长
		time.Sleep(time.Millisecond)
	}
	wg.Done()
	println("doAllocate done")
}
func doIdleAdd(n int64, wg *sync.WaitGroup) {
	var res int64
	for i := int64(0); i < n; i++ {
		res += i
	}
	wg.Done()
	println("doIdleAdd done")
}
func main() {
	// runtime.GOMAXPROCS(runtime.NumCPU()) // needed before go 1.5
	start:=time.Now()
	wg := new(sync.WaitGroup)
	wg.Add(2)
	go doAllocate(50*1024, wg) // 申请内存空间 50MB, 约50秒
	t := int64(math.Pow(10, 11))
	go doIdleAdd(t, wg) // 执行加法，大约会执行 30 秒，方便观察运行情况
	wg.Wait()
	fmt.Println(time.Since(start))
}
